package cn.edu.hfut.dmic.webcollector.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class FileUtils {
	public static final Logger LOG = LoggerFactory.getLogger(FileUtils.class);
    
	public static void writeFileWithMaxKbs(File fileLast,String content,long maxKbs){
		StringTokenizer token = new StringTokenizer(content, "\r\n");
		String fileTempPath = fileLast.getAbsolutePath().substring(0,fileLast.getAbsolutePath().lastIndexOf("_"));
		String ext = fileLast.getName().substring(fileLast.getName().lastIndexOf(".") + 1);
		String index = fileLast.getName().substring(fileLast.getName().lastIndexOf("_") + 1,fileLast.getName().lastIndexOf("."));
		try{
			FileWriter fw = new FileWriter(fileLast, true);
			BufferedWriter bw = new BufferedWriter(fw);
			String line = null;
			int fileIndex = Integer.valueOf(index);
			long readNum = fileLast.length();
			while(token.hasMoreTokens()){
				line = token.nextToken() + "\r\n";
				readNum += line.getBytes().length;
				if(readNum <= maxKbs * 1024){
					bw.write(line);
				}else{
					bw.flush();
					fw.flush();
					bw.close();
					fw.close();
					
					fileIndex++;
					
					fileLast = new File(fileTempPath + "_" + fileIndex + "." + ext);
					if(!fileLast.exists()){
						fileLast.createNewFile();
					}
					fw = new FileWriter(fileLast, true);
					bw = new BufferedWriter(fw);
					bw.write(line);
					readNum = line.getBytes().length;
				}
			}
			bw.flush();
			fw.flush();
			bw.close();
			fw.close();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
    
    public static void deleteDir(File dir){
        File[] filelist=dir.listFiles();
        for(File file:filelist){
            if(file.isFile()){
                file.delete();
            }else{
                deleteDir(file);
            }
        }
        dir.delete();
    }
    
    public static void copy(File origin,File newfile) throws FileNotFoundException, IOException{
        if(!newfile.getParentFile().exists()){
            newfile.getParentFile().mkdirs();
        }
        FileInputStream fis=new FileInputStream(origin);
        FileOutputStream fos=new FileOutputStream(newfile);
        byte[] buf=new byte[2048];
        int read;
        while((read=fis.read(buf))!=-1){
            fos.write(buf,0,read);
        }
        fis.close();
        fos.close();
    }
    
    public static void writeFile(String filename,String contentStr,String charset) throws FileNotFoundException, IOException{
        byte[] content=contentStr.getBytes(charset);
        FileOutputStream fos=new FileOutputStream(filename);
        fos.write(content);
        fos.close();
    }
    
    public static void writeFile(File file,String contentStr,String charset) throws FileNotFoundException, IOException{
    	if(!file.exists()){
    		file.createNewFile();
    	}
        byte[] content=contentStr.getBytes(charset);
        FileOutputStream fos=new FileOutputStream(file);
        fos.write(content);
        fos.close();
    }
    
	public static void writeFileAppend(File file, String contentStr,
			String charset) throws FileNotFoundException, IOException {
		byte[] content = contentStr.getBytes(charset);
		FileOutputStream fos = new FileOutputStream(file, true);
		fos.write(content);
		fos.close();
	}
	
    
    public static void writeFileWithParent(String filename,String contentStr,String charset) throws FileNotFoundException, IOException{
        File file=new File(filename);
        File parent=file.getParentFile();
        if(!parent.exists()){
            parent.mkdirs();
        }
        byte[] content=contentStr.getBytes(charset);
        FileOutputStream fos=new FileOutputStream(file);
        fos.write(content);
        fos.close();
    }
    
    public static void writeFileWithParent(File file,String contentStr,String charset) throws FileNotFoundException, IOException{
        File parent=file.getParentFile();
        if(!parent.exists()){
            parent.mkdirs();
        }
        byte[] content=contentStr.getBytes(charset);
        FileOutputStream fos=new FileOutputStream(file);
        fos.write(content);
        fos.close();
    }
    
    public static void writeFile(String filename,byte[] content) throws FileNotFoundException, IOException{
        FileOutputStream fos=new FileOutputStream(filename);
        fos.write(content);
        fos.close();
    }
    
    
    
    public static void writeFile(File file,byte[] content) throws FileNotFoundException, IOException{
        FileOutputStream fos=new FileOutputStream(file);
        fos.write(content);
        fos.close();
    }
    
    public static void writeFileWithParent(String filename,byte[] content) throws FileNotFoundException, IOException{
        File file=new File(filename);
        File parent=file.getParentFile();
        if(!parent.exists()){
            parent.mkdirs();
        }
        FileOutputStream fos=new FileOutputStream(file);
        fos.write(content);
        fos.close();
    }
    
    public static void writeFileWithParent(File file,byte[] content) throws FileNotFoundException, IOException{
       
        File parent=file.getParentFile();
        if(!parent.exists()){
            parent.mkdirs();
        }
        FileOutputStream fos=new FileOutputStream(file);
        fos.write(content);
        fos.close();
    }
    
    public static byte[] readFile(File file) throws IOException{
        FileInputStream fis = new FileInputStream(file);
        byte[] buf = new byte[2048];
        int read;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((read = fis.read(buf)) != -1) {
            bos.write(buf, 0, read);
        }

        fis.close();
        return bos.toByteArray();
    }
    
    /**
	 * 读取txt配置文件
	 * @param filePath
	 * @param typeNo
	 * @return
	 */
	public static StringBuffer readTxtFile(String filePath,String split) {
		StringBuffer sb = new StringBuffer();
		InputStreamReader read = null;
		BufferedReader bufferedReader = null;
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				read = new InputStreamReader(new FileInputStream(file),encoding);// 考虑到编码格式
				bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					sb.append(lineTxt).append(split);
				}
				read.close();
			} else {
				LOG.info("找不到指定的文件");
			}
		} catch (Exception e) {
			LOG.info("读取文件内容出错");
			e.printStackTrace();
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
				if (read != null) {
					read.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb;
	}
	
	public static void createFolder(String fileName){
		String folder = fileName.substring(0,fileName.lastIndexOf("/"));
		File file = new File(folder);
		if(!file.exists()){
			file.mkdirs();
		}
	}
    
}
